package com.f_mai.im;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.EventNotificationContent;
import cn.jpush.im.android.api.content.MessageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.enums.MessageDirect;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.api.BasicCallback;

public class MsgListAdapter extends BaseAdapter {

	private static final String TAG = "MsgListAdapter";
	private Activity activity;
	private Conversation mConv;
	private List<Message> mMsgList = new ArrayList<Message>();// 所有消息列表

	public MsgListAdapter(Activity activity, String targetUser) {
		this.activity = activity;
		mConv = JMessageClient.getSingleConversation(targetUser);
		if (mConv != null) {
			this.mMsgList = mConv.getAllMessage();
		}
	}
	public MsgListAdapter(Activity activity, long groupId) {
		this.activity = activity;
		mConv = JMessageClient.getGroupConversation(groupId);
		if (mConv != null) {
			this.mMsgList = mConv.getAllMessage();
		}
	}

	@Override
	public int getCount() {
		return mMsgList.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public int getViewTypeCount() {
		return 2;
	}

	@Override
	public int getItemViewType(int position) {
		Message msg = mMsgList.get(position);
		if (msg.getDirect().equals(MessageDirect.send)) {
			return 1;
		} else {
			return 0;
		}
	}

	public void addMsgToList(Message msg) {
		mMsgList.add(msg);
		notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Message msg = mMsgList.get(position);
		int type = getItemViewType(position);
		if (convertView == null) {
			switch (type) {
			case 0:
				convertView = activity.getLayoutInflater().inflate(R.layout.chat_item_receive_text, null);
				break;
			case 1:
				convertView = activity.getLayoutInflater().inflate(R.layout.chat_item_send_text, null);
				break;
			}
		}
		TextView send_time_txt = null;
		TextView msg_content = null;
		TextView display_name_tv = null;
		ImageView sending_iv = null;
		ImageButton fail_resend_ib = null;
		send_time_txt = (TextView) convertView.findViewById(R.id.send_time_txt);
		msg_content = (TextView) convertView.findViewById(R.id.msg_content);
		switch (type) {
		case 0:
			display_name_tv = (TextView) convertView.findViewById(R.id.display_name_tv);
			display_name_tv.setText(msg.getFromName());
			break;
		case 1:
			sending_iv =(ImageView) convertView.findViewById(R.id.sending_iv);
			fail_resend_ib = (ImageButton) convertView.findViewById(R.id.fail_resend_ib);
			break;
		}
		send_time_txt.setText(new TimeFormat(activity, msg.getCreateTime()).getDetailTime());
		if (msg.getContent() instanceof EventNotificationContent) {
			msg_content.setText(((EventNotificationContent) msg.getContent()).getEventText());
		} else if (msg.getContent() instanceof TextContent){
			msg_content.setText(((TextContent) msg.getContent()).getText());
		}else {
			msg_content.setText(((MessageContent) msg.getContent()).toJson());
		}
		if (position != 0) {
			long lastDate = mMsgList.get(position - 1).getCreateTime();
			// 如果两条消息之间的间隔超过十分钟则显示时间
			if (msg.getCreateTime() - lastDate > 600000) {
				TimeFormat timeFormat = new TimeFormat(activity, msg.getCreateTime());
				send_time_txt.setText(timeFormat.getDetailTime());
				send_time_txt.setVisibility(View.VISIBLE);
			} else {
				send_time_txt.setVisibility(View.GONE);
			}
		} else {
			TimeFormat timeFormat = new TimeFormat(activity, msg.getCreateTime());
			send_time_txt.setText(timeFormat.getDetailTime());
		}
		checkTxtMsg(msg,position,sending_iv,fail_resend_ib);
		return convertView;
	}

	private void checkTxtMsg(final Message msg, final int position, final ImageView sendingIv, final ImageButton resend) {
		// 检查发送状态，发送方有重发机制
		if (msg.getDirect().equals(MessageDirect.send)) {
			final Animation sendingAnim = AnimationUtils.loadAnimation(activity, R.anim.rotate);
			LinearInterpolator lin = new LinearInterpolator();
			sendingAnim.setInterpolator(lin);
			switch (msg.getStatus()) {
			case send_success:
				if (sendingAnim != null) {
					sendingIv.clearAnimation();
					sendingIv.setVisibility(View.GONE);
				}
				resend.setVisibility(View.GONE);
				break;
			case send_fail:
				if (sendingAnim != null) {
					sendingIv.clearAnimation();
					sendingIv.setVisibility(View.GONE);
				}
				resend.setVisibility(View.VISIBLE);
				break;
			case send_going:
				sendingIv.setVisibility(View.VISIBLE);
		        sendingIv.startAnimation(sendingAnim);
		        resend.setVisibility(View.GONE);
		        //消息正在发送，重新注册一个监听消息发送完成的Callback
		        if (!msg.isSendCompleteCallbackExists()) {
		            msg.setOnSendCompleteCallback(new BasicCallback() {
		                @Override
		                public void gotResult(final int status, final String desc) {
		                    refresh();
		                }
		            });
		        }
				break;
			default:
			}
			// 点击重发按钮，重发消息
			resend.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					resendTextOrVoice(sendingIv,resend,sendingAnim,msg);
				}
			});
		}
	}
	private void resendTextOrVoice(final ImageView sendingIv, final ImageButton resend, Animation sendingAnim, Message msg) {
        resend.setVisibility(View.GONE);
        sendingIv.setVisibility(View.VISIBLE);
        sendingIv.startAnimation(sendingAnim);

        if (!msg.isSendCompleteCallbackExists()) {
            msg.setOnSendCompleteCallback(new BasicCallback() {
                @Override
                public void gotResult(final int status, String desc) {
                    if (status != 0) {
                        sendingIv.clearAnimation();
                        sendingIv.setVisibility(View.GONE);
                        resend.setVisibility(View.VISIBLE);
                        Toast.makeText(activity, "重发失败", Toast.LENGTH_SHORT).show();
                    }
                    refresh();
                }
            });
        }
        JMessageClient.sendMessage(msg);
    }
	public void refresh() {
		mMsgList.clear();
		if (mConv != null) {
			mMsgList = mConv.getAllMessage();
			notifyDataSetChanged();
		}
	}
}
